package com.mx.tool.form.window;

import com.intellij.openapi.project.Project;
import com.mx.tool.commit.CommitMessage;
import com.mx.tool.commit.Type;

import javax.swing.*;
import java.util.Enumeration;

/**
 * @Author: mengxiang.
 * @create: 2021-03-08 10:06
 * @Description:
 */
public class CommitPanel {
    private JPanel mainPanel;
    private JTextField description;
    private ButtonGroup changeTypeGroup;
    private JRadioButton featRadioButton;
    private JRadioButton fixRadioButton;
    private JRadioButton docsRadioButton;
    private JRadioButton styleRadioButton;
    private JRadioButton refactorRadioButton;
    private JRadioButton testRadioButton;

    public CommitPanel(Project project, CommitMessage commitMessage) {
        if (commitMessage != null) {
            restoreValuesFromParsedCommitMessage(commitMessage);
        }
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }

    public CommitMessage getCommitMessage() {
        return new CommitMessage(
                getSelectedType(),
                description.getText().trim()
        );
    }

    private Type getSelectedType() {
        for (Enumeration<AbstractButton> buttons = changeTypeGroup.getElements(); buttons.hasMoreElements(); ) {
            AbstractButton button = buttons.nextElement();

            if (button.isSelected()) {
                return Type.valueOf(button.getActionCommand().toUpperCase());
            }
        }
        return null;
    }

    private void restoreValuesFromParsedCommitMessage(CommitMessage commitMessage) {
        if (commitMessage.type() != null) {
            for (Enumeration<AbstractButton> buttons = changeTypeGroup.getElements(); buttons.hasMoreElements(); ) {
                AbstractButton button = buttons.nextElement();

                if (button.getActionCommand().equalsIgnoreCase(commitMessage.type().label())) {
                    button.setSelected(true);
                }
            }
        }
        description.setText(commitMessage.shortDescription());
    }
}
